import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
import legacy from '@vitejs/plugin-legacy';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
import unocss from 'unocss/vite';
import simpleHtmlPlugin from 'vite-plugin-simple-html';

// 包装环境变量，转换布尔值、数字
function wrapperEnv(env) {
  const result = {};

  for (const key in env) {
    if (Object.hasOwnProperty.call(env, key)) {
      let value = env[key];

      if (value === 'true') {
        result[key] = true;
      } else if (value === 'false') {
        result[key] = false;
      } else if (!isNaN(value)) {
        result[key] = Number(value);
      } else {
        result[key] = value;
      }
    }
  }

  return result;
}

export default defineConfig(({ command, mode }) => {
  const isBuild = command === 'build';
  const env = loadEnv(mode, process.cwd());

  console.log('Current mode:', mode);
  console.log('command', command);
  console.log('env', env);


  const viteEnv = wrapperEnv(env);

  console.log('viteEnv', viteEnv);



  const { VITE_TITLE, VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY, VITE_API_URL } = viteEnv;
  console.log('VITE_API_URL', VITE_API_URL);

  return {
    base: './',
    plugins: [
      legacy({
        targets: ['chrome 80', 'defaults', 'not IE 11'],
      }),
      vue(),
      AutoImport({
        imports: ['vue', 'vue-router'], // 自动导入 Vue 和 Vue Router
        dts: true, // 自动生成类型声明文件
      }),
      Components({
        // 自动导入组件插件
        // resolvers: [NaiveUiResolver()],
      }),
      VueSetupExtend(),
      unocss(),
      simpleHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: VITE_TITLE,
          },
        },
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    server: {
      proxy: {
        '/api': {
          target: 'http://app.jssnu.mangxu.cn',  // 确保目标地址正确
          changeOrigin: true,  // 改变请求头中的Origin，解决跨域问题
          rewrite: (path) => path.replace(/^\/api/, ''),  // 去掉前缀 /api
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 配置了 SCSS 的预处理选项
          // additionalData: `@import '@/styles/variables.scss';`,
        },
      },
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: false,
    },
    optimizeDeps: {
      include: ['vue', 'vue-router'], // 添加需要优化的依赖项
    },
  };
});
